package main

import (
	"cloudnative/metrics"
	"fmt"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"log"
	"math/rand"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	metrics.Register()
	signals := make(chan os.Signal)
	done := make(chan struct{})
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		sig := <-signals
		fmt.Println(sig)
		done <- struct{}{}
	}()
	mux := http.NewServeMux()
	mux.HandleFunc("/", handler)
	mux.HandleFunc("/healthz", healthz)
	mux.HandleFunc("/hello", helloHandler)
	mux.Handle("/metrics", promhttp.Handler())

	srv := http.Server{
		Addr:    ":80",
		Handler: mux,
	}
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()
	<-done
}

func healthz(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
	w.Write([]byte("OK"))
}

func randInt(min int, max int) int {
	rand.Seed(time.Now().UTC().UnixNano())
	return min + rand.Intn(max-min)
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	timer := metrics.NewTimer()
	defer timer.ObserveTotal()
	delay := randInt(0, 2000)
	time.Sleep(time.Millisecond * time.Duration(delay))
	w.Write([]byte("hello"))
}

func handler(w http.ResponseWriter, r *http.Request) {
	for i, _ := range r.Header {
		w.Header().Set(i, r.Header.Get(i))
	}
	version := os.Getenv("VERSION")
	w.Header().Set("VERSION", version)
	ip, _ := remoteIp(r)
	fmt.Println(ip)
}

func remoteIp(req *http.Request) (string, error) {
	ip, _, err := net.SplitHostPort(req.RemoteAddr)
	if err != nil {
		log.Fatalf("Getting req.RemoteAddr %v", err)
		return "", err
	}
	userIP := net.ParseIP(ip)

	return userIP.String(), nil
}
